<template>
  <view class="container">
    <scroll-view ref="scrollRef" class="chat-container" scroll-y >
      <view v-for="(msg, index) in messages" :key="index" :id="msg.messageUId">
        <view class="time">{{ transformTime(msg.sentTime) }}</view>
        <view class="message" :class="{ 'self': msg.messageDirection == 1}">
          <view class="context">
            <image :src="msg.messageDirection == 1 ? userInfoStore.userInfo.avatar : targetInfo.avatar" style="width: 80rpx;height:80rpx;border-radius: 16rpx"/>
            <view class="content">{{ msg.content.content }}</view>
          </view>
        </view>
      </view>
    </scroll-view>
    <view class="input-area border-top">
      <input type="text" placeholder="输入消息..." v-model="inputMsg" @confirm="sendMessage" class="border"/>
      <button @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import {ref} from 'vue';
import * as RongIMLib from '@rongcloud/imlib-next'
import {onLoad} from "@dcloudio/uni-app";
import {transformTime} from "@/utils/utils";
import {loginApi} from "@/api";
import {userStore} from "@/store/modules/user";

const scrollRef = ref() // 聊天内容区域
const inputMsg = ref(''); // 输入框内容
const messages = ref([]); // 模拟的聊天消息
const targetId = ref(''); // 目标用户ID
const userInfoStore = userStore() // 当前用户信息
const targetInfo = ref({}) // 目标用户信息d

// 发送消息
const sendMessage = () => {
  if (inputMsg.value.trim() == '') return
  // 指定消息发送的目标会话
  let conversation = {
    targetId: targetId.value, // targetId
    conversationType: RongIMLib.ConversationType.PRIVATE // 会话类型：RongIMLib.ConversationType.PRIVATE | RongIMLib.ConversationType.GROUP
  };

  // 构建文本消息
  const message = new RongIMLib.TextMessage({
    content: inputMsg.value,
    user : uni.getStorageSync('user'),
  })
  inputMsg.value = ''; // 清空输入框

// 发送消息
  RongIMLib.sendMessage(conversation, message).then(({ code, data }) => {
    if (code === 0) {
      // getHistory()
      messages.value.push(data)
      console.log('消息发送成功：', data)
    } else {
      console.log('消息发送失败：', code)
    }
  });
}

// 获取历史消息
const getHistory = async () => {
  const conversation = {
    conversationType: RongIMLib.ConversationType.PRIVATE,
    targetId: targetId.value
  }

  // 从当前时间开始向前查询
  const option = {
    timestamp: 0,
    count: 20,
    order: 0
  }

  RongIMLib.getHistoryMessages(conversation,option).then(res => {
    console.log(res.data)
    if (res.code === 0) {
      console.log('历史消息',res.data.list)
      console.log('是否还有更多',res.data.hasMore)
      messages.value = messages.value.concat(res.data.list)
    } else {
      console.log(res.code, res.msg)
      uni.navigateTo({
        url: '/pages/login/login'
      })
    }
  })
}

// 获取目标用户信息
const getUserInfo = async () => {
  let res = await loginApi.getUserInfoByIds({ids: targetId.value})
  targetInfo.value = res.data[0]
}

onLoad((option)=>{
  uni.setNavigationBarTitle({
    title: option.name
  })
  targetId.value = option.id
  getHistory()
  getUserInfo()
  uni.$on('receiveMessage', (msg) => {
    if(msg.targetId === targetId.value){
      messages.value.push(msg)
      console.log(messages.value)
    }
  })
})

</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
}

.chat-container {
  height: calc(100vh - 44px - 60px);
  background: #fff;
}

.message {
  margin: 10rpx 0;
  padding: 10px;
  border-radius: 10px;
  &.self{
    align-self: flex-end;
    .context{
      flex-direction: row-reverse;
      .content{
        background-color: #b3e5fc;
      }
    }
  }
  &:not(.self) {
    align-self: flex-start;
    .context{
      flex-direction: row;
      .content{
        background-color: #e0e0e0;
      }
    }
  }
  .context{
    display: flex;
    align-items: center;
    .content{
      max-width: 70%;
      margin: 0 20rpx;
      display: flex;
      align-items: center;
      padding: 10rpx;
      border-radius: 10rpx;
    }
    .tip{
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
    }
  }
}

.time {
  text-align: center;
  font-size: 12px;
  color: #999;
}

.input-area {
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  padding: 10px;
  background-color: #fff;
  box-sizing: border-box;
}

.input-area input {
  flex: 1;
  height: 40px;
  padding: 0 10px;
}

.input-area button {
  height: 40px;
  margin-left: 10px;
}
</style>